package com.openatc.agent.service.impl;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.openatc.agent.model.Fault;
import com.openatc.agent.model.FaultRange;
import com.openatc.agent.resmodel.PageOR;
import com.openatc.agent.service.AscsDao;
import com.openatc.agent.service.FaultDao;
import com.openatc.agent.service.FaultService;
import com.openatc.comm.data.MessageData;
import com.openatc.core.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

@Service
public class FaultServiceImpl implements FaultService {

    private Logger log = Logger.getLogger(FaultServiceImpl.class.toString());

    @Autowired
    FaultDao faultDao;

    @Autowired(required = false)
    AscsDao ascsDao;

    @Value("${fault.filepath}")
    private String faultFilePath;

    @Value("${ftpclient.port}")
    private int port;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    Gson gson = new Gson();

    @Autowired
    private CommonService commonService;


    public void processFaultMessage(MessageData msg) {
        String agentid = msg.getAgentid();
        Fault[] m_faultDeque = gson.fromJson(msg.getData().getAsJsonObject().getAsJsonArray("m_FaultDeque"), Fault[].class);

        for (Fault fault : m_faultDeque) {
            fault.setEnumerate("0");
            fault.setAgentid(agentid);
            fault.setModel("asc");
            fault.setEventType("status/fault");
            fault.setDeleteFlag("0");
            faultDao.save(fault);
        }
    }

    @Override
    public PageOR<JsonObject> getFaultPageOR(FaultRange faultRange) {
        String tmpTableName = "tmp_dev";
        String faultBaseSql = String.format("select f.agentid,f.m_w_faultid,f.m_by_fault_board_type,f.m_by_fault_desc_value,f.m_by_fault_level," +
                "f.m_un_fault_occur_time,f.m_un_fault_renew_time,f.m_w_fault_type,f.m_w_sub_fault_type,f.delete_flag,f.enumerate," +
                "f.model,f.operation_time,f.operator,f.event_type,%s.name as devname from fault f",tmpTableName);
        String joinSql = commonService.createJoinSql(tmpTableName);
        String onSql = String.format(" ON f.agentid = %s.agentid",tmpTableName);
        String whereCondition = getFaultWhereCondition(faultRange);
        // 分页条件
        String limitCondition = createLimitCondition(faultRange);

        String orderBy = " ORDER BY m_un_fault_occur_time desc ";
        String countBase = String.format("select count(*) from fault f");
        String countSql = countBase.concat(joinSql).concat(onSql).concat(whereCondition);
        String searchSql = faultBaseSql.concat(joinSql).concat(onSql).concat(whereCondition).concat(orderBy).concat(limitCondition);

        int count = jdbcTemplate.queryForObject(countSql, int.class);
        PageOR<JsonObject> pageOR = new PageOR<>();

        List<JsonObject> faults = jdbcTemplate.query(searchSql, new RowMapper<JsonObject>() {
            @Override
            public JsonObject mapRow(ResultSet rs, int rowNum) throws SQLException {
                JsonObject fault = new JsonObject();
                fault.addProperty("agentid",rs.getString("agentid"));
                fault.addProperty("deleteFlag",rs.getString("delete_flag"));
                fault.addProperty("enumerate",rs.getString("enumerate"));
                fault.addProperty("eventType",rs.getString("event_type"));
                fault.addProperty("mUnFaultOccurTime",rs.getLong("m_un_fault_occur_time"));
                fault.addProperty("m_byFaultBoardType",rs.getInt("m_by_fault_board_type"));
//                fault.add("m_byFaultDescValue",processFaultDescValue(rs.getBytes("m_by_fault_desc_value")));
                fault.add("m_byFaultDescValue",processFaultDescValue(rs.getBinaryStream("m_by_fault_desc_value")));
                fault.addProperty("m_byFaultLevel",rs.getInt("m_by_fault_level"));
                fault.addProperty("m_unFaultOccurTime", processFaultTime(rs.getLong("m_un_fault_occur_time")));
                fault.addProperty("m_unFaultRenewTime",processFaultTime(rs.getLong("m_un_fault_renew_time")));
                fault.addProperty("m_wFaultID",rs.getLong("m_w_faultid"));
                fault.addProperty("m_wFaultType",rs.getInt("m_w_fault_type"));
                fault.addProperty("m_wSubFaultType",rs.getInt("m_w_sub_fault_type"));
                fault.addProperty("model",rs.getString("model"));
                fault.addProperty("name",rs.getString("devname"));
                fault.addProperty("operationTime",processFaultTime(rs.getLong("operation_time")));
                fault.addProperty("operator",rs.getString("operator"));
                return fault;
            }
        });

        pageOR.setTotal((long)count);
        pageOR.setContent(faults);

        return pageOR;
    }

    /**
     * 处理故障时间
     * long转字符串
     * @param time
     * @return
     */
    private String processFaultTime(long time) {
        return time == 0 ? "0" : DateUtil.longToString(time * 1000);
    }

    private JsonArray processFaultDescValue(InputStream is) {
        Object descValue = null;
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(is);
            descValue = ois.readObject();
        } catch (Exception e) {
            log.warning("read fault desc value failed! " + e.getMessage());
        } finally {
            if (is!=null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        JsonArray value = null;
        if (descValue != null) {
            int[] values =  (int[]) descValue;
            JsonElement jsonElement = gson.toJsonTree(values);
            value = jsonElement.getAsJsonArray();
        }
        return value;
    }


    private String createLimitCondition(FaultRange faultRange) {
        String limit = "";
        if (faultRange.getPageNum() != null && faultRange.getPageRow() != null) {
            int pageNum = faultRange.getPageNum() - 1;
            int pageRow = faultRange.getPageRow();
            if (pageNum < 0)
                pageNum = 0;
            limit = String.format(" limit  %d  offset  %d ",pageRow, pageNum*pageRow );
        }

        return limit;
    }

    /**
     * 根据传入的数据拼接查询条件
     * @param faultRange
     * @return
     */
    private String getFaultWhereCondition(FaultRange faultRange) {
        String where = "";
        String tmp = "";
        // 是否删除条件
        tmp = String.format(" delete_flag = '%s'",0);
        where = commonService.addWhereCondition(where,tmp);
        // agentid条件
        if (StringUtils.hasLength(faultRange.getAgentId())) {
            tmp = String.format(" f.agentid = '%s'",faultRange.getAgentId());
            where = commonService.addWhereCondition(where,tmp);
        }
        // 确认结果条件
        if (StringUtils.hasLength(faultRange.getEnumerate())) {
            tmp = String.format(" enumerate = '%s'",faultRange.getEnumerate());
            where = commonService.addWhereCondition(where,tmp);
        }
        // 板卡类型条件
        if (faultRange.getM_byFaultBoardType() != null) {
            tmp = String.format(" m_by_fault_board_type = %s",faultRange.getM_byFaultBoardType());
            where = commonService.addWhereCondition(where,tmp);
        }
        // 主故障类型条件
        if (faultRange.getM_wFaultType() != null) {
            tmp = String.format(" m_w_fault_type = %s",faultRange.getM_wFaultType());
            where = commonService.addWhereCondition(where,tmp);
        }
        // 当前故障条件
        if (faultRange.getIsCurrentFault() != null &&faultRange.getIsCurrentFault()) {
            tmp = String.format(" m_un_fault_renew_time = %s",0);
            where = commonService.addWhereCondition(where,tmp);
        }
        // 故障发生时间条件
        if (StringUtils.hasLength(faultRange.getBeginTime()) && StringUtils.hasLength(faultRange.getEndTime())) {
            String beginTime = faultRange.getBeginTime();
            String endTime = faultRange.getEndTime();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long bTime;
            long eTime;
            try {
                bTime = format.parse(beginTime).getTime() / 1000;
                eTime = format.parse(endTime).getTime() / 1000;
            } catch (ParseException e) {
                bTime = 0;
                eTime = System.currentTimeMillis();
            }

            tmp = String.format(" m_un_fault_occur_time between %s and %s",bTime,eTime);
            where = commonService.addWhereCondition(where,tmp);
        }
        return where;
    }

    /**
     * @Author: yangyi
     * @Date: 2021/11/23 10:56
     * @Description: 重组msg,去掉不需要的msg部分
     */
    public MessageData filterMsg(MessageData msg) {
        String agentid = msg.getAgentid();
        Fault[] m_faultDeque = gson.fromJson(msg.getData().getAsJsonObject().getAsJsonArray("m_FaultDeque"), Fault[].class);
        List<Fault> faultList = new ArrayList<Fault>();
        for (Fault fault : m_faultDeque) {
            fault.setMUnFaultOccurTime(fault.getM_unFaultOccurTime());
            Long m_wFaultID = fault.getM_wFaultID();
            List<Fault> list = faultDao.findByAgentidAndM_wFaultID(agentid,m_wFaultID);
            if (list != null && list.size() > 0) { // 记录已存在
                Fault fa = list.get(0);
                String enuneRate = fa.getEnumerate(); //
                if (enuneRate.equals("1") || enuneRate.equals("2")) { //已处理、已忽略
                    continue;
                } else {
                    faultList.add(fault);
                }
            } else {
                faultList.add(fault);
            }
        }
        Fault[] targetFaultList = faultList.toArray(new Fault[0]);
        // 重新组装msg
        JsonElement jeData = msg.getData().deepCopy();
        jeData.getAsJsonObject().remove("m_FaultDeque");
        jeData.getAsJsonObject().add("m_FaultDeque", gson.toJsonTree(targetFaultList, Fault[].class));
        msg.setData(jeData);
        return msg;
    }

    /**
     * 根据用户角色获取设备id
     * @return
     */
    public List<String> getAgentidListByUserRole() {
        String whereCondition = "";
        String code = ascsDao.getSqlByUserRole();
        if (code != null){
            String temp = code;
            whereCondition = ascsDao.addWhereCondition(whereCondition,temp);
        }

        String sql = "SELECT agentid FROM dev";
        sql = sql.concat(whereCondition);
        List<String> agentids = ascsDao.getAgentidsBySql(sql);
        return agentids;
    }
}
